home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1997 February / EnigmA AMIGA RUN 15 (1997)(G.R. Edizioni)(IT)[!][issue 1997-02][PLANET CD V].iso / enigma / onlypc / java / samples.bin / EmployeeDataManager.java < prev    next >
Text File  |  1996-05-13  |  15KB  |  732 lines

  1. /*
  2.  * Title: Employee Data Manager
  3.  * Type: Application
  4.  * Source: EmployeeDataManager.java
  5.  * Description:
  6.  *    Reads and parses a text file containing employee information; parses,
  7.  *    and sorts the information based on name, section number or SS# (selected
  8.  *    by user).  The information is then displayed in a scrollable text window.
  9.  */
  10.  
  11. import java.awt.*;
  12. import java.applet.*;
  13. import java.io.*;
  14.  
  15. /**
  16.  * A simple one-directional external linked list class.
  17.  */
  18.  
  19. class LinkList extends Object
  20. {
  21.     private LinkList therest;
  22.     private Object thevalue;
  23.  
  24.     public LinkList(Object obj)
  25.     {
  26.         therest = null;
  27.         thevalue = obj;
  28.     }
  29.  
  30.     /**
  31.      * Create a new list node; insert it at the head of the list. Return the list.
  32.      */
  33.  
  34.     public LinkList cons(Object obj)
  35.     {
  36.         LinkList newnode = new LinkList(obj);
  37.         newnode.thevalue = thevalue;
  38.         newnode.therest = therest;
  39.         therest = newnode;
  40.         thevalue = obj;
  41.         return this;
  42.     }
  43.  
  44.     /**
  45.      * The object owned by the list node
  46.      */
  47.  
  48.     public Object value()
  49.     {
  50.         return thevalue;
  51.     }
  52.  
  53.     /**
  54.      * The remainder of the list
  55.      */
  56.  
  57.     public LinkList rest()
  58.     {
  59.         return therest;
  60.     }
  61.  
  62.     /**
  63.      * Swap the values of a and b.
  64.      */
  65.     public static void swapValues(LinkList a, LinkList b)
  66.     {
  67.         Object save = a.thevalue;
  68.         a.thevalue = b.thevalue;
  69.         b.thevalue = save;
  70.     }
  71. }
  72.  
  73. /**
  74.  * An employee name object. Allows creation, validation, and ordering of names.
  75.  */
  76.  
  77. class Name
  78. {
  79.     String val;
  80.     final static int MAX_LENGTH = 30;
  81.  
  82.     Name(String v)
  83.     {
  84.         val = v;
  85.     }
  86.  
  87.     String value()
  88.     {
  89.         return val;
  90.     }
  91.  
  92.     public boolean isValid()
  93.     {
  94.         return (0 < val.length()) && (val.length() <= MAX_LENGTH);
  95.     }
  96.  
  97.     public boolean isGreaterThan(Name n)
  98.     {
  99.         return val.compareTo(n.val) > 0;
  100.     }
  101. }
  102.  
  103. /**
  104.  * An employee section object. Allows creation, validation, and ordering of employee sections.
  105.  */
  106.  
  107. class Section
  108. {
  109.     int val;
  110.     final static int MAX_LENGTH = 10;
  111.  
  112.     Section(int a)
  113.     {
  114.         val = a;
  115.     }
  116.  
  117.     Section(String a)
  118.     throws NumberFormatException
  119.     {
  120.         System.out.println("Parsing section; a='" + a + "' (" + a.length() + " chars)");
  121.         val = Integer.parseInt(a.trim());
  122.     }
  123.  
  124.     int value()
  125.     {
  126.         return val;
  127.     }
  128.  
  129.     public boolean isValid()
  130.     {
  131.         return val > 0;
  132.     }
  133.  
  134.     public boolean isGreaterThan(Section a)
  135.     {
  136.         return val > a.value();
  137.     }
  138. }
  139.  
  140. /**
  141.  * An employee social-security number object. Allows creation, validation, and
  142.  * ordering of employee SS #'s.
  143.  */
  144.  
  145. class SSN
  146. {
  147.     String val;
  148.     final static int MAX_LENGTH = 11;
  149.  
  150.     SSN(String s)
  151.     {
  152.         val = s;
  153.     }
  154.  
  155.     String value()
  156.     {
  157.         return val;
  158.     }
  159.  
  160.     public boolean isValid()
  161.     {
  162.         if (val.length() > MAX_LENGTH) return false;
  163.         if (val.charAt(3) != '-') return false;
  164.         if (val.charAt(6) != '-') return false;
  165.         try
  166.         {
  167.             Integer.parseInt(val.substring(0, 2));
  168.             Integer.parseInt(val.substring(4, 5));
  169.             Integer.parseInt(val.substring(7, 10));
  170.         }
  171.         catch (NumberFormatException e)
  172.         {
  173.             return false;
  174.         }
  175.         return true;
  176.     }
  177.  
  178.     public boolean isGreaterThan(SSN s)
  179.     {
  180.         return val.compareTo(s.val) > 0;
  181.     }
  182. }
  183.  
  184. /**
  185.  * Exception signaling an invalid employee data object
  186.  */
  187.  
  188. class InvalidEmployeeException extends Exception
  189. {
  190.     public String toString()
  191.     {
  192.         return "InvalidEmployeeException";
  193.     }
  194.  
  195.     public String getMessage()
  196.     {
  197.         return "The Employee information is invalid";
  198.     }
  199. }
  200.  
  201. /**
  202.  * A completely constructed employee data object.
  203.  */
  204.  
  205. class Employee
  206. {
  207.     public Name name;
  208.     public Section section;
  209.     public SSN ssn;
  210.  
  211.     final static int NAME_FLD = 0;
  212.     final static int AGE_FLD = 1;
  213.     final static int SSN_FLD = 2;
  214.  
  215.     public Employee(Name n, Section a, SSN s)
  216.     throws InvalidEmployeeException
  217.     {
  218.         name = n;
  219.         if (!name.isValid()) throw new InvalidEmployeeException();
  220.         section = a;
  221.         if (!section.isValid()) throw new InvalidEmployeeException();
  222.         ssn = s;
  223.         if (!ssn.isValid()) throw new InvalidEmployeeException();
  224.     }
  225.  
  226.     public Employee(String n, String a, String s)
  227.     throws InvalidEmployeeException
  228.     {
  229.         this(new Name(n), new Section(a), new SSN(s));
  230.     }
  231.  
  232.     public String toString()
  233.     {
  234.         String s;
  235.         s = (name.value()).trim();
  236.         s += " ";
  237.         s += (String.valueOf(section.value())).trim();
  238.         s += " ";
  239.         s += (ssn.value()).trim();
  240.         s += "\r\n";
  241.         return s;
  242.     }
  243. }
  244.  
  245. /**
  246.  * A state-ful list of employee data objects.
  247.  */
  248.  
  249. class EmployeeList
  250. {
  251.     LinkList fir = null;
  252.     LinkList cur = null;
  253.  
  254.     public void add(Employee e)
  255.     {
  256.         if (cur == null) fir = new LinkList(e);
  257.         else fir = fir.cons(e);
  258.         cur = fir;
  259.     }
  260.  
  261.     /**
  262.      * Sort the employee list on one of the three fields: name, section, or SS#
  263.      */
  264.  
  265.     public void sort(int fld)
  266.     {
  267.         // Use a bubble sort, for simplicity
  268.  
  269.         LinkList e = fir;
  270.         while (e != null)
  271.         {
  272.             LinkList ee = e.rest();
  273.             while (ee != null)
  274.             {
  275.                 switch (fld)
  276.                 {
  277.                 case Employee.NAME_FLD:
  278.                     if
  279.                     (
  280.                             (((Employee)(e.value())).name).
  281.                             isGreaterThan
  282.                             ((((Employee)(ee.value()))).name)
  283.                     )
  284.                         LinkList.swapValues(e, ee);
  285.                     break;
  286.                 case Employee.AGE_FLD:
  287.                     if
  288.                     (
  289.                             (((Employee)(e.value())).section).
  290.                             isGreaterThan
  291.                             ((((Employee)(ee.value()))).section)
  292.                     )
  293.                         LinkList.swapValues(e, ee);
  294.                     break;
  295.                 case Employee.SSN_FLD:
  296.                     if
  297.                     (
  298.                             (((Employee)(e.value())).ssn).
  299.                             isGreaterThan
  300.                             ((((Employee)(ee.value()))).ssn)
  301.                     )
  302.                         LinkList.swapValues(e, ee);
  303.                     break;
  304.                 }
  305.                 ee = ee.rest();
  306.             }
  307.             e = e.rest();
  308.         }
  309.     }
  310.  
  311.     /**
  312.      * Return the first employee in the list
  313.      */
  314.  
  315.     public Employee first()
  316.     {
  317.         cur = fir;
  318.         if (cur == null) return null; else return (Employee)(cur.value());
  319.     }
  320.  
  321.     /**
  322.      * Return the next employee in the list
  323.      */
  324.  
  325.     public Employee next()
  326.     {
  327.         if (cur == null) return null; else cur = cur.rest();
  328.         if (cur == null) return null; else return (Employee)(cur.value());
  329.     }
  330. }
  331.  
  332. /**
  333.  * Provide file storage and retrieval of employee data objects.
  334.  */
  335.  
  336. class EmployeeFileAccessor
  337. {
  338.     RandomAccessFile f;
  339.  
  340.     /**
  341.      * Open the employee file; create it if it does not exist.
  342.      */
  343.  
  344.     public EmployeeFileAccessor(String fname)
  345.     throws IOException
  346.     {
  347.         f = new RandomAccessFile(fname, "rw");
  348.     }
  349.  
  350.     /**
  351.      * Set the employee file to the beginning
  352.      */
  353.  
  354.     public void reset()
  355.     throws IOException
  356.     {
  357.         f.seek(0);
  358.     }
  359.  
  360.     // The size, in bytes, of an employee record. Records are fixed-size, to
  361.     // allow for easy modification.
  362.  
  363.     final static int recsize =
  364.         Name.MAX_LENGTH+1 + Section.MAX_LENGTH+1 + SSN.MAX_LENGTH+1 +1;
  365.  
  366.     /**
  367.      * Write a new employee to the end of the file
  368.      */
  369.  
  370.     public void addEmployee(Employee e)
  371.     throws IOException
  372.     {
  373.         // Transfer field values to buffer
  374.         byte[] b = new byte[recsize];
  375.         int pos = 0;
  376.  
  377.         int len = e.name.value().length();
  378.         e.name.value().getBytes(0, len, b, pos);
  379.         b[pos + len] = '\0';
  380.         pos += Name.MAX_LENGTH + 1;
  381.  
  382.         String a = String.valueOf(e.section.value());
  383.         len = a.length();
  384.         a.getBytes(0, len, b, pos);
  385.         b[pos + len] = '\0';
  386.         pos += Section.MAX_LENGTH + 1;
  387.  
  388.         len = e.ssn.value().length();
  389.         e.ssn.value().getBytes(0, len, b, pos);
  390.         b[pos + len] = '\0';
  391.  
  392.         b[recsize-1] = '\n';
  393.  
  394.         // Write buffer to file, as a fixed-size record
  395.         f.seek(f.length());
  396.         f.write(b);
  397.     }
  398.  
  399.     /**
  400.      * Fetch the first or next employee from the file.
  401.      */
  402.  
  403.     public Employee getNextEmployee()
  404.     throws IOException
  405.     {
  406.         byte[] b = new byte[recsize];
  407.         int nchars;
  408.         System.out.println("About to read");
  409.         if ((nchars = f.read(b)) <= 0) return null;
  410.         System.out.println("Read " + nchars + " chars");
  411.         int pos = 0;
  412.         String n = new String(b, 0, pos, Name.MAX_LENGTH);
  413.         n = n.trim();
  414.         System.out.println("Fetched name='" + n + "'");
  415.         pos += Name.MAX_LENGTH + 1;
  416.         String a = new String(b, 0, pos, Section.MAX_LENGTH);
  417.         a = a.trim();
  418.         System.out.println("Fetched section=" + a);
  419.         pos += Section.MAX_LENGTH + 1;
  420.         String s = new String(b, 0, pos, SSN.MAX_LENGTH);
  421.         s = s.trim();
  422.         System.out.println("Fetched ssn=" + s);
  423.  
  424.         Employee emp;
  425.         try
  426.         {
  427.             emp = new Employee(n, a, s);
  428.         }
  429.         catch (InvalidEmployeeException e)
  430.         {
  431.             System.out.println("Invalid employee read from file!");
  432.             return null;
  433.         }
  434.  
  435.         return emp;
  436.     }
  437.  
  438.     /**
  439.      * Read the employee file, and build a list of employee objects.
  440.      */
  441.  
  442.     EmployeeList buildEmployeeList()
  443.     {
  444.         EmployeeList elist = new EmployeeList();
  445.         Employee emp;
  446.         int noOfEmployees = 0;
  447.         try
  448.         {
  449.             reset();
  450.         }
  451.         catch (IOException ex)
  452.         {
  453.             return elist;
  454.         }
  455.         for (;;)
  456.         {
  457.             try
  458.             {
  459.                 emp = getNextEmployee();
  460.             }
  461.             catch (IOException ex)
  462.             {
  463.                 return elist;
  464.             }
  465.             if (emp == null) break;
  466.             noOfEmployees++;
  467.             elist.add(emp);
  468.         }
  469.         System.out.println("noOfEmployees=" + noOfEmployees);
  470.         return elist;
  471.     }
  472. }
  473.  
  474. /**
  475.  * Demonstration of the employee data manager classes.
  476.  * Allows the user to scroll through the list of employees; sort the list on
  477.  * either name, section, or SS#; enter information for a new employee; and store
  478.  * that information in the file.
  479.  */
  480.  
  481. public class EmployeeDataManager extends Applet
  482. {
  483.     //
  484.     // The name of the employee data file...
  485.     //
  486.     final static String employeeFileName = "employee.dat";
  487.  
  488.     /*Panel addPanel;
  489.     Panel sortPanel;
  490.     Choice choice;
  491.     Button sortbutton;
  492.     Button addbutton;
  493.     TextArea ta;
  494.     TextField nfield;
  495.     TextField afield;
  496.     TextField sfield;*/
  497.     EmployeeFileAccessor efa;
  498.  
  499.     EmployeeDataManager()
  500.     {
  501.         // Call the superclass constructor (for Applet)
  502.         super();
  503.     }
  504.  
  505.     /**
  506.      * Update the display with the current contents of the employee list.
  507.      */
  508.  
  509.     void updateEmployeeDisplay(EmployeeList elist)
  510.     {
  511.         Employee emp = elist.first();
  512.         String textdata = "";
  513.         for (;;)
  514.         {
  515.             if (emp == null) break;
  516.             System.out.println("Appending " + emp.toString() + " to textarea");
  517.             textdata += emp.toString();
  518.             emp = elist.next();
  519.         }
  520.         ta.setText(textdata);
  521.         repaint();
  522.     }
  523.  
  524.     // Every Applet should have the following method:
  525.     public void init()
  526.     {
  527.  
  528.         //name 30, section 10, ssn 11 == 51
  529.  
  530.         //{{INIT_CONTROLS
  531.         setLayout(new BorderLayout());
  532.         addPanel=new Panel();
  533.         add("North",addPanel);
  534.         addPanel.reshape(2,2,618,58);
  535.         sortPanel=new Panel();
  536.         add("Center",sortPanel);
  537.         sortPanel.reshape(3,67,617,120);
  538.         label1=new Label("Name:");
  539.         addPanel.add(label1);
  540.         label1.reshape(6,24,37,18);
  541.         nfield=new TextField(22);
  542.         addPanel.add(nfield);
  543.         nfield.reshape(51,24,187,16);
  544.         label2=new Label("Section#:");
  545.         addPanel.add(label2);
  546.         label2.reshape(250,24,55,16);
  547.         afield=new TextField(7);
  548.         addPanel.add(afield);
  549.         afield.reshape(313,24,63,16);
  550.         label3=new Label(" SS#:");
  551.         addPanel.add(label3);
  552.         label3.reshape(388,24,28,16);
  553.         sfield=new TextField(14);
  554.         addPanel.add(sfield);
  555.         sfield.reshape(422,24,116,16);
  556.         addbutton=new Button("Add");
  557.         addPanel.add(addbutton);
  558.         addbutton.reshape(554,19,47,29);
  559.         choice= new Choice();
  560.         sortPanel.add(choice);
  561.         choice.reshape(21,22,111,25);
  562.         choice.addItem("Sort By name");
  563.         choice.addItem("Sort By Section");
  564.         choice.addItem("Sort By SSN");
  565.         sortbutton=new Button("Sort");
  566.         sortbutton.setFont(new Font("Dialog",Font.PLAIN,12));
  567.         sortPanel.add(sortbutton);
  568.         sortbutton.reshape(156,21,80,32);
  569.         ta=new TextArea(5,39);
  570.         sortPanel.add(ta);
  571.         ta.reshape(245,18,328,87);
  572.         //}}
  573.  
  574.         // Open the employee file
  575.         System.out.println("Opening file");
  576.         try
  577.         {
  578.             efa = new EmployeeFileAccessor(employeeFileName);
  579.             System.out.println("File opened");
  580.         }
  581.         catch (IOException e)
  582.         {
  583.             System.out.println("Unable to open file " + employeeFileName);
  584.             return;
  585.         }
  586.  
  587.         // Fetch all employees from file, and display them in the text area
  588.         EmployeeList elist = efa.buildEmployeeList();
  589.         updateEmployeeDisplay(elist);
  590.  
  591.         layout();
  592.  
  593.     }
  594.  
  595.     // Every Applet should have the following method:
  596.     public void start()
  597.     {
  598.     }
  599.  
  600.     // Every Applet should have the following method:
  601.     public void stop()
  602.     {
  603.     }
  604.  
  605.     public boolean handleEvent(Event e)
  606.     {
  607.         if ((e.target == sortbutton) && (e.id == Event.ACTION_EVENT))
  608.         {
  609.             // The SORT button was pressed; perform sort
  610.             EmployeeList elist = efa.buildEmployeeList();
  611.             elist.sort(choice.getSelectedIndex());
  612.             System.out.println("Sort on field " + choice.getSelectedIndex());
  613.  
  614.             // Redisplay the employee data
  615.             updateEmployeeDisplay(elist);
  616.  
  617.         }
  618.         else if ((e.target == addbutton) && (e.id == Event.ACTION_EVENT))
  619.         {
  620.             Employee emp;
  621.  
  622.             // The ADD button was pressed; add new employee
  623.             System.out.println("Add an employee");
  624.  
  625.             // Create (and validate) an employee object
  626.             try
  627.             {
  628.                 emp = new Employee
  629.                     (nfield.getText(), afield.getText(), sfield.getText());
  630.             }
  631.             catch (Exception ex1)
  632.             {
  633.                 System.out.println("Invalid employee data");
  634.                 //showStatus("Invalid employee data; please re-enter");
  635.                 return true;
  636.             }
  637.  
  638.             // Add the employee to the file
  639.             try
  640.             {
  641.                 efa.addEmployee(emp);
  642.             }
  643.             catch (IOException ex2)
  644.             {
  645.                 System.out.println("Unable to add employee to file");
  646.                 return true;
  647.             }
  648.  
  649.             System.out.println("Employee added");
  650.  
  651.             // Redisplay the employee data
  652.             EmployeeList elist = efa.buildEmployeeList();
  653.             updateEmployeeDisplay(elist);
  654.  
  655.  
  656.             return true;
  657.         }
  658.         else if (e.id == Event.WINDOW_DESTROY)
  659.         {
  660.             System.exit(0);
  661.         }
  662.         return false;
  663.     }
  664.  
  665.     public void paint(Graphics g)
  666.     {
  667.     }
  668.  
  669.     public static void main(String argv[])
  670.     {
  671.         // Create a Frame
  672.         MainFrame f = new MainFrame("EmployeeDataManager");
  673.  
  674.         // Instantiate the Applet
  675.         EmployeeDataManager applet = new EmployeeDataManager();
  676.  
  677.         // Add the Applet to the Frame (Frame's use BorderLayout)
  678.         f.add("Center", applet);
  679.  
  680.         // Init and start the Applet
  681.         applet.init();
  682.         applet.start();
  683.  
  684.         // Resize and show the Frame
  685.         f.resize(600, 200);
  686.         f.move(50, 50);
  687.         //f.layout();
  688.         f.show();
  689.  
  690.     }
  691.  
  692.     public String getAppletInfo()
  693.     {
  694.         return "EmployeeDataManager";
  695.     }
  696.  
  697.     //{{DECLARE_CONTROLS
  698.     Panel addPanel;
  699.     Panel sortPanel;
  700.     Label label1;
  701.     TextField nfield;
  702.     Label label2;
  703.     TextField afield;
  704.     Label label3;
  705.     TextField sfield;
  706.     Button addbutton;
  707.     Choice choice;
  708.     Button sortbutton;
  709.     TextArea ta;
  710.     //}}
  711. }
  712.  
  713. class MainFrame extends Frame
  714. {
  715.     public MainFrame(String s) {
  716.       super(s);
  717.     }
  718.  
  719.     // Handle close events by simply exiting
  720.     public boolean handleEvent(Event e) {
  721.     if (e.id == Event.WINDOW_DESTROY) {
  722.         System.exit(0);
  723.     }
  724.     return false;
  725.     }
  726. }
  727.  
  728.  
  729.  
  730.  
  731.  
  732.